import { Ref, ref, watch } from 'vue';

export function useGisScene(
  sceneId: Ref<string | null>,
  api: Function,
): {
  elementid: string;
  viewer3D: Ref<any>;
  app: Ref<any>;
  resize: () => void;
} {
  const viewer3D = ref();
  const app = ref();
  let viewToken = '';

  const elementid = `bfps-${Math.random().toString(36)}`;

  // 监听模型id是否发生改变，若改变则销毁之前的模型，然后再创建新模型。
  watch(
    () => sceneId.value,
    (newValue) => {
      if (newValue) {
        destroyApp();
        loadBimface();
      }
    },
    { immediate: true, deep: true },
  );

  // 调整窗口长宽
  function resize() {
    viewer3D.value.resize(
      document.documentElement.clientWidth,
      document.documentElement.clientHeight - 40,
    );
  }

  // 渲染成功回调
  function successCallback() {
    // 判断是否为3D模型
    // 获取DOM元素
    const webAppConfig = new window.Glodon.Bimface.Application.WebApplicationGISConfig();
    const domShow = document.getElementById(elementid);
    webAppConfig.domElement = domShow;

    webAppConfig.Toolbars = []
    webAppConfig.Buttons = []
    webAppConfig.enableViewHouse = false
    // 设置全局单位
    // webAppConfig.globalUnit = window.Glodon.Bimface.Common.Units.LengthUnits.Millimeter;
    // 创建WebApplication
    app.value = new window.Glodon.Bimface.Application.WebApplicationGIS(webAppConfig);
    // 添加待显示的模型
    // app.value.addView(viewToken);
    // 从WebApplication获取viewer3D对象
    viewer3D.value = app.value.getViewer();


    // feature1：设置摄像机状态
    let cameraState = {
      "name": "persp",
      "position": {
        "x": 438234.1310180214,
        "y": -155202.79759646222,
        "z": 145060.75410098155
      },
      "target": {
        "x": 681281.9375708819,
        "y": 87845.47780185359,
        "z": 17421.865765899973
      },
      up: {
        "x": 0.24615725369566935,
        "y": 0.2461538102468012,
        "z": 0.9374512830830133
      },
      "fov": 90
    };
    function setCameraStatus() {
      // position：相机位置，即相机镜头所在空间坐标点，采用世界坐标系
      // target：目标点位置，即相机捕捉场景目标点所在空间坐标点，采用世界坐标系
      // up：相机上方朝向，表示相机姿态的空间向量，与主视线方向（即position-target向量）垂直 (默认为z-up)
      // fov：视角范围，单位为角度，通常取值在60-90°之间
      // aspect：视野角度的宽高比
      // near：最近可视距离
      // far：最远可视距离
      // zoom：图像缩放比
      //  viewer3D.value.getCameraStatus();
      viewer3D.value.setCameraStatus(cameraState);
      // console.log("zptest:viewer3D.value",viewer3D.value)
    }
    // feature2: 选中模型
    function getData(data) {
      console.log("zptest:click:", data);
      
    }
    function setClickListener() {
      viewer3D.value.addEventListener(window.Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked, getData);
    
    }
    setClickListener()
    // feature3：聚焦到某一个构件上面
    function setZoomToComponents() {
      // viewer3D.value.getModel().clearSelectedComponents();
      // viewer3D.value.getModel().selectByIds(["450859"]);
      // viewer3D.value.getModel().zoomToSelectedComponents();
    }
    setTimeout(() => {
      setZoomToComponents()
    }, 3000);


    function zoomToBoundingBox() {
      let boundingbox = {
          "min": {
              "x": -9496.219279454494,
              "y": -4299.299971053061,
              "z": 999.9607157957682
          },
          "max": {
              "x": 8443.779875881222,
              "y": 6382.751044860747,
              "z": 9475.048556778615
          }
      }
      viewer3D.value.getCamera().zoomToBoundingBox(boundingbox);
  }
    setTimeout(() => {
      // setCameraStatus()
      // viewer3D.value.getInfoBar().destroy()
      // viewer3D.value.getEventManager().destroy()
      // viewer3D.value.getEffectManager().destroy()
      // viewer3D.value.getLayerManager().destroy()
      // viewer3D.value.getLightManager().destroy()
      // viewer3D.value.getScaleBar().destroy()


      let layerManager = viewer3D.value.getLayerManager();

      // 根据图层ID获取对应图层对象(bimlayer )
      let layer = layerManager.getLayer('layer_10000834451088');
      // layerManager.zoomToLayer('layer_10000834451088')

      
      // viewer3D.value.setSelectedComponentsById(["342141"])
      // 着色 | 透明 | 
      // https://bimface.com/docs/model-viewer/v1/api-reference/Glodon.Bimface.ElementManager.ComponentManager.html
      // layer.getComponentManager().overrideColor({all:true},new window.Glodon.Web.Graphics.Color(255,0,0,1));
      // layer.getComponentManager().overrideColor({ids:['593313']},new window.Glodon.Web.Graphics.Color(255,0,0,1));
      // layer.getComponentManager().blink({ids:['593313']},new window.Glodon.Web.Graphics.Color(255,0,0,1));
      layer.getComponentManager().select({ids:['593313']});
      layer.getComponentManager().select({ids:['593313']});
      // console.log("layer.getComponentManager:",layer.getComponentManager().select({all:true}))
      // zoomToBoundingBox()
      
    }, 2000);

    // feature2:显示



    viewer3D.value.addScene(viewToken);
  }

  // 渲染失败回调
  function failureCallback(error) {
    console.log(error);
  }

  function loadBimface() {
    if (!sceneId.value) {
      return;
    }

    api({ key: 'sceneId', value: sceneId.value })
      .then((res) => {
        viewToken = res.data;

        // 初始化显示组件
        const loaderConfig = new window.BimfaceSDKLoaderConfig();
        loaderConfig.viewToken = viewToken;
        window.BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
      })
      .catch((error) => {
        console.error(error);
      });
  }

  // 销毁app
  function destroyApp() {
    if (app.value) {
      app.value.destroy();
    }
  }

  return {
    elementid,
    viewer3D,
    app,
    resize,
  };
}
